package cn.ug.mall.web.controller;

import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.core.SerializeObjectError;
import cn.ug.enums.RateKeyEnum;
import cn.ug.feign.MemberUserService;
import cn.ug.feign.PayTbillService;
import cn.ug.feign.VersionService;
import cn.ug.mall.bean.*;
import cn.ug.mall.bean.InvestBoardBean;
import cn.ug.mall.mapper.entity.InvestBoardParamBean;
import cn.ug.mall.mapper.entity.PublicityInfoBean;
import cn.ug.mall.mapper.entity.PublicityInfoParamBean;
import cn.ug.mall.service.RateSettingsService;
import cn.ug.mall.web.submit.RateSettingSubmit;
import cn.ug.util.UF;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * @author zhaohg
 * @date 2018/07/06.
 */
@RestController
@RequestMapping("/setting")
public class RateSettingsController {

    @Autowired
    private RateSettingsService rateSettingsService;
    @Autowired
    private VersionService versionService;
    @Autowired
    private MemberUserService memberUserService;
    @Autowired
    private PayTbillService payTbillService;


    /**
     * 查找费率参数设置
     * @param accessToken
     * @param keyName
     * @return
     */
    @RequestMapping(value = "/find/{keyName}" , method = GET)
    public SerializeObject findByKeyName(
            @RequestHeader("accessToken") String accessToken,
            @PathVariable("keyName") String keyName) {

        return rateSettingsService.findByKeyName(keyName,accessToken);
    }

    /**
     * 获取首页顶部标题栏/app底部导航栏，显示/隐藏的版本
     * @param accessToken
     * @param keyName
     * @param showTag
     * @return
     */
    @RequestMapping(value = "/find/appAudit/{keyName}", method = GET)
    public SerializeObject findAppIndexTopTitle(@RequestHeader("accessToken") String accessToken,@PathVariable("keyName") String keyName,Integer showTag){
        showTag = (showTag==null) ? 1 : showTag;
        if (showTag > 1 || showTag < 0) {
            return new SerializeObjectError("00000002");
        }

        keyName = UF.toString(keyName);
//        if (RateKeyEnum.GOLD_INVEST.getKey().equalsIgnoreCase(keyName) || RateKeyEnum.MARKET_INFO.getKey().equalsIgnoreCase(keyName)) {
//            keyName = RateKeyEnum.APP_BOTTOM_NAVIGATION.getKey();
//        }
        SerializeObject object = rateSettingsService.findByKeyName(keyName,accessToken);
        if (null == object.getData()) {
            return object;
        }
        //显示的版本
        SerializeObject<List<String>> showData = rateSettingsService.findShowVersions(keyName);
        List<String> showVersions = showData.getData();

        //隐藏的版本
        if (showTag == 0) {
            SerializeObject<List<String>> data = versionService.findAllVersions();
            List<String> allVersions = data.getData();
            List<String> hideVersions = allVersions.stream().filter(item -> !showVersions.contains(item)).collect(Collectors.toList());
            return new SerializeObject<>(ResultType.NORMAL, hideVersions);
        }

        if (showTag == 1) {
            return new SerializeObject<>(ResultType.NORMAL, showVersions);
        }
        return new SerializeObject<>(ResultType.ERROR, new ArrayList<>());
    }

    /**
     * 设置app过审模块,首页顶部标题栏/app底部导航栏，显示/隐藏的版本
     * @param accessToken
     * @param keyName
     * @param showTag
     * @return
     */
    @RequestMapping(value = "/appAudit/updateVersion" , method = POST)
    public SerializeObject updateShowVersion(@RequestHeader("accessToken") String accessToken,String keyName,Integer showTag,String[] versions){
        showTag = (showTag==null) ? 1 : showTag;
        if (showTag > 1 || showTag < 0) {
            return new SerializeObjectError("00000002");
        }

        keyName = UF.toString(keyName);

        SerializeObject object = rateSettingsService.findByKeyName(keyName,accessToken);
        if (null == object.getData()) {
            return object;
        }
        //showTag = (showTag==null || showTag < 0) ? 1 : showTag;
        List<String> versionList = new ArrayList<>();
        if (versions != null && versions.length > 0) {
            versionList = new ArrayList<String>();
            for (String versionio : versions) {
                versionList.add(versionio);
            }
        }

        List<String> showVersions = new ArrayList<>();
        //隐藏版本修改
        if (showTag == 0) {
            SerializeObject<List<String>> data = versionService.findAllVersions();
            List<String> allVersions = data.getData();
            List<String> finalVersionList = versionList;
            showVersions = allVersions.stream().filter(item -> !finalVersionList.contains(item)).collect(Collectors.toList());

            return rateSettingsService.updateShowVesion(keyName,1,showVersions);
        }

        //显示版本修改
        if (showTag == 1) {
            showVersions = versionList;
            return rateSettingsService.updateShowVesion(keyName,1,showVersions);
        }

        return new SerializeObject<>(ResultType.ERROR, "修改失败");
    }

    /**
     * app端接口
     * 查看某个顶部标题栏/app底部导航栏，在某个版本下，是否隐藏:1,显示；0，隐藏
     * @param accessToken
     * @param keyName
     * @param version
     * @return
     */
    @RequestMapping(value = "/appAudit/findShowTag", method = GET)
    public SerializeObject findShowTag(String keyName, String version){

        if (StringUtils.isBlank(version)) {
            return new SerializeObject<>(ResultType.ERROR, "版本号为空");
        }

        keyName = UF.toString(keyName);
//        if (RateKeyEnum.GOLD_INVEST.getKey().equalsIgnoreCase(keyName) || RateKeyEnum.MARKET_INFO.getKey().equalsIgnoreCase(keyName)) {
//            keyName = RateKeyEnum.APP_BOTTOM_NAVIGATION.getKey();
//        }
        SerializeObject object = rateSettingsService.findByKeyName(keyName,"");
        if (null == object.getData()) {
            return object;
        }

        //显示的版本
        SerializeObject<List<String>> showData = rateSettingsService.findShowVersions(keyName);
        List<String> showVersions = showData.getData();
        if (showVersions.contains(version)) {
            return new SerializeObject<>(ResultType.NORMAL, 1);
        }

        return new SerializeObject<>(ResultType.NORMAL, 0);
    }

    /**
     * app端-查询显示的导航栏
     * @return
     */
    @RequestMapping(value = "/findShowNavigation",method = GET)
    public SerializeObject findShowNavigation(String version) {
        if (StringUtils.isBlank(version)) {
            return new SerializeObject<>(ResultType.ERROR, "版本号为空");
        }
        List list = new ArrayList();
        //显示的版本
        SerializeObject<List<String>> goldInvestData = rateSettingsService.findShowVersions(RateKeyEnum.GOLD_INVEST.getKey());
        List<String> goldInvestVersions = goldInvestData.getData();
        if (goldInvestVersions.contains(version)) {
            list.add(RateKeyEnum.GOLD_INVEST.getKey());
        }
        SerializeObject<List<String>> marketInfoData = rateSettingsService.findShowVersions(RateKeyEnum.MARKET_INFO.getKey());
        List<String> marketInfoVersions = marketInfoData.getData();
        if (marketInfoVersions.contains(version)) {
            list.add(RateKeyEnum.MARKET_INFO.getKey());
        }

        return new SerializeObject(ResultType.NORMAL,list);
    }

    /**
     * 查询：品宣信息,是否隐藏,运营修正数据,客户作息时间,热销标签
     * @param keyName
     * @return
     */
    @RequestMapping(value = "/publicity/query", method = GET)
    public SerializeObject findPublicity(){
        SerializeObject<PublicityInfoBean> infoBean = rateSettingsService.findPublicity();
        if (null != infoBean) {
            PublicityInfoBean resultBean = infoBean.getData();
            //获取平台累计已为用户管理黄金克重（千克）
            SerializeObject gramData = payTbillService.findPlatformTotalGram();
            Integer gram = (Integer) gramData.getData();
            BigDecimal totalGram = new BigDecimal(gram).divide(new BigDecimal(1000)).setScale(2, BigDecimal.ROUND_HALF_UP);
            resultBean.setTotalGoldGram(totalGram);
            resultBean.setAppTotalGoldGram(gram + resultBean.getInputGoldGram() * 1000);

            //获取平台累计服务用户（万人）
            SerializeObject userData = memberUserService.countTotalUsers();
            Integer user = (Integer)userData.getData();
            BigDecimal totalUser = new BigDecimal(user).divide(new BigDecimal(10000)).setScale(2, BigDecimal.ROUND_HALF_UP);
            resultBean.setTotalServeUser(totalUser);
            resultBean.setAppTotalServeUser(user + resultBean.getInputServeUser() * 10000);

            return new SerializeObject<>(ResultType.NORMAL, resultBean);
        }

        return new SerializeObject<>(ResultType.ERROR, "获取失败");
    }

    /**
     * app端：获取平台回租总克重，注册用户数（加运营修正数）
     * @param accessToken
     * @return
     */
    @RequestMapping(value = "/getPlatformTotal", method = GET)
    public SerializeObject findPlatformData (@RequestHeader("accessToken") String accessToken) {
        SerializeObject<PublicityInfoBean> infoBean = rateSettingsService.findPublicity();
        if (null != infoBean) {
            PublicityInfoBean resultBean = infoBean.getData();
            resultBean.setTotalGoldGram(resultBean.getTotalGoldGram() == null ? BigDecimal.ZERO : resultBean.getTotalGoldGram());
            resultBean.setTotalServeUser(resultBean.getTotalServeUser() == null ? BigDecimal.ZERO : resultBean.getTotalServeUser());
            SerializeObject gramData = payTbillService.findPlatformTotalGram();
            SerializeObject userData = memberUserService.countTotalUsers();
            BigDecimal totalGram = new BigDecimal((Integer) gramData.getData()).divide(new BigDecimal(1000)).setScale(2, BigDecimal.ROUND_HALF_UP);
            BigDecimal totalUser = new BigDecimal((Integer)userData.getData()).divide(new BigDecimal(10000)).setScale(2, BigDecimal.ROUND_HALF_UP);

            Map map = new HashMap();
            map.put("totalGoldGram",totalGram.add(new BigDecimal(resultBean.getInputGoldGram())));
            map.put("totalServeUser",totalUser.add(new BigDecimal(resultBean.getInputServeUser())));
            return new SerializeObject<>(ResultType.NORMAL, map);
        }
        return new SerializeObject<>(ResultType.ERROR, "获取失败");
    }

    /**
     * 修改：品宣信息配置
     * @param accessToken
     * @param keyName
     * @param showTag
     * @return
     */
    @RequestMapping(value = "/publicity/update", method = GET)
    public SerializeObject updatePublicity(@RequestHeader("accessToken") String accessToken, PublicityInfoParamBean paramBean){
        if (paramBean == null) {
            return new SerializeObjectError("00000002");
        }
        if (paramBean.getAboutUsTag() == null || paramBean.getPlatformDataTag() == null || paramBean.getCustomerServiceScheduleTag() == null) {
            return new SerializeObjectError("00000002");
        }
        if ((paramBean.getAboutUsTag() != 1 && paramBean.getAboutUsTag() != 0)
                || (paramBean.getPlatformDataTag() != 1 && paramBean.getPlatformDataTag() != 0)
                || (paramBean.getCustomerServiceScheduleTag() != 1 && paramBean.getCustomerServiceScheduleTag() != 0)) {
            return new SerializeObjectError("00000002");
        }
        if (paramBean.getPlatformDataTag() == 1 && ((paramBean.getInputGoldGram() == null || paramBean.getInputGoldGram() < 0 || paramBean.getInputGoldGram() > 999999999)
                || (paramBean.getInputServeUser() == null || paramBean.getInputServeUser() < 0 || paramBean.getInputServeUser() > 999999999))) {
            return new SerializeObjectError("00000002");
        }

        if (paramBean.getCustomerServiceScheduleTag() == 1 && StringUtils.isBlank(paramBean.getAmTime()) && StringUtils.isBlank(paramBean.getPmTime())) {
            return new SerializeObjectError("00000002");
        }
        return rateSettingsService.updatePublicityByParam(paramBean);
    }

    /**
     * 查询：黄金投资底部-平台数据,是否隐藏，运营修正数据
     * @param accessToken
     * @param keyName
     * @return
     */
    @RequestMapping(value = "/publicity/{keyName}", method = GET)
    public SerializeObject findplatformData(@RequestHeader("accessToken") String accessToken, @PathVariable("keyName") String keyName){
        if (StringUtils.isBlank(keyName)) {
            return new SerializeObject<>(ResultType.ERROR, "keyName为空");
        }
        keyName = UF.toString(keyName);
        SerializeObject object = rateSettingsService.findByKeyName(keyName,accessToken);
        if (null == object.getData()) {
            return object;
        }
        Map map = (Map) object.getData();
        if (RateKeyEnum.ABOUT_US.getKey().equalsIgnoreCase(keyName)) {
            return new SerializeObject<>(ResultType.NORMAL, map.get("showTag"));
        }

        return new SerializeObject<>(ResultType.ERROR, "获取失败");
    }

    /**
     * 获取投资版块配置
     * @param accessToken
     * @return
     */
    @RequestMapping(value = "/investArea/query", method = GET)
    public SerializeObject findInvest(){
        SerializeObject<InvestBoardBean> infoBean = rateSettingsService.findInvestArea();
        if (null != infoBean) {
            InvestBoardBean resultBean = infoBean.getData();

            return new SerializeObject<>(ResultType.NORMAL, resultBean);
        }

        return new SerializeObject<>(ResultType.ERROR, "获取失败");
    }

    /**
     * 修改投资版块配置
     * @param accessToken
     * @param paramBean
     * @return
     */
    @RequestMapping(value = "/investArea/update", method = GET)
    public SerializeObject updateInvest(@RequestHeader("accessToken") String accessToken, InvestBoardParamBean paramBean){
        if (paramBean == null) {
            return new SerializeObjectError("00000002");
        }

        if (paramBean.getBusinessShowTag() == null || paramBean.getInvestDynamicShowTag() == null) {
            return new SerializeObject<>(ResultType.ERROR, "是否隐藏字段不能为空");
        }
        if ((paramBean.getBusinessShowTag() != 0 && paramBean.getBusinessShowTag() != 1)
                || (paramBean.getInvestDynamicShowTag() != 0 && paramBean.getInvestDynamicShowTag() != 1)) {
            return new SerializeObject<>(ResultType.ERROR, "是否隐藏字段只能为1或0");
        }

        List<BusinessIntroduction> introductions = new ArrayList<>();
        if (StringUtils.isNotBlank(paramBean.getBusinessIntroductions())) {
            BusinessIntroductionBean businessIntroductionBean = JSON.parseObject(paramBean.getBusinessIntroductions(), BusinessIntroductionBean.class);
            introductions = businessIntroductionBean.getBusinessIntroductions();
        }
        List<ModuleTitle> moduleTitles = new ArrayList<>();
        if (StringUtils.isNotBlank(paramBean.getProductModuleList())) {
            ModuleTitleBean moduleTitleBean = JSON.parseObject(paramBean.getProductModuleList(),ModuleTitleBean.class);
            moduleTitles = moduleTitleBean.getModuleTitles();
        }

        if (paramBean.getBusinessShowTag() == 1 && (CollectionUtils.isEmpty(introductions) || introductions.size() > 4)) {
            return new SerializeObject<>(ResultType.ERROR, "业务介绍至少配置1条，至多配置4条");
        }

        if (paramBean.getBusinessShowTag() == 1 && !CollectionUtils.isEmpty(introductions)) {
            for (BusinessIntroduction businessIntroduction : introductions) {
                if (businessIntroduction != null && StringUtils.isBlank(businessIntroduction.getTitle()) && StringUtils.isNotBlank(businessIntroduction.getLink())) {
                    return new SerializeObject<>(ResultType.ERROR, "业务介绍未配置标题时，不能配置链接");
                }
                if (businessIntroduction != null && StringUtils.isNotBlank(businessIntroduction.getTitle()) && StringUtils.isBlank(businessIntroduction.getLink())) {
                    return new SerializeObject<>(ResultType.ERROR, "业务介绍配置标题时，必须同时配置链接");
                }
                if (businessIntroduction != null && !businessIntroduction.getLink().startsWith("http://") && !businessIntroduction.getLink().startsWith("https://")) {
                    return new SerializeObject<>(ResultType.ERROR, "链接必须以http://或https://开头");
                }
            }
        }

        if (paramBean.getInvestDynamicShowTag() == 1 && (paramBean.getInvestReadNum() == null || paramBean.getInvestReadNum() <= 0)) {
            return new SerializeObject<>(ResultType.ERROR, "投资动态条目数值必须是正整数，且不能为空");
        }

        paramBean.setIntroductions(introductions);
        paramBean.setModuleTitles(moduleTitles);
        return rateSettingsService.updateInvestAreaByParam(paramBean);
    }

    /**
     * 获取产品展示区配置
     * @return
     */
    @RequestMapping(value = "/investArea/productModule", method = GET)
    public SerializeObject<List<ModuleTitle>> findProductModule(){
        SerializeObject<List<ModuleTitle>> moduleTitles = rateSettingsService.findProductModule();
        if (null != moduleTitles && null != moduleTitles.getData()) {

            return new SerializeObject<List<ModuleTitle>>(ResultType.NORMAL, moduleTitles.getData());
        }
        return new SerializeObject<>(ResultType.ERROR, "获取失败");
    }

    /**
     * 客户端接口
     * @param keyName
     * @return
     */
    @GetMapping
    public SerializeObject get(String keyName) {
        return rateSettingsService.findByKeyName(keyName,null);
    }

    @RequestMapping(value = "/operate/{keyName}" , method = POST)
    public SerializeObject add(
            @RequestHeader("accessToken") String accessToken,
            @PathVariable("keyName") String keyName,
            RateSettingSubmit submit) {

        return rateSettingsService.operate(keyName, submit);
    }

    /**
     * 设置优惠模板
     * @param accessToken
     * @param privilegeTemplateBean
     * @return
     */
    @RequestMapping(value = "/privilegeTemplate/save" , method = POST)
    public SerializeObject privilegeTemplateSave(@RequestHeader("accessToken") String accessToken,PrivilegeTemplateBean privilegeTemplateBean) {
        return rateSettingsService.save(privilegeTemplateBean);
    }

    /**
     * 根据模板类型查询模板 1.买金优惠模板  2.回租优惠模板
     * @return
     */
    @RequestMapping(value = "/privilegeTemplate/findTemplateByType" , method = GET)
    public SerializeObject  findTemplateByType(@RequestHeader("accessToken") String accessToken,Integer type){
        return rateSettingsService.findTemplateByType(type);
    }

    /**
     * 根据id查询优惠模板
     * @param accessToken
     * @param id
     * @return
     */
    @RequestMapping(value = "/privilegeTemplate/findById" , method = GET)
    public SerializeObject  findById(@RequestHeader("accessToken") String accessToken,Integer id){
        return rateSettingsService.findById(id);
    }

    /**
     * 删除模板
     * @param accessToken
     * @param id
     * @return
     */
    @RequestMapping(value = "/privilegeTemplate/delete" , method = GET)
    public SerializeObject  delete(@RequestHeader("accessToken") String accessToken,Integer id){
        return rateSettingsService.delete(id);
    }

    /**
     * 优惠模板开关
     * @param accessToken
     * @param id
     * @param status 1:启用 2:停用
     * @return
     */
    @RequestMapping(value = "/privilegeTemplate/switch" , method = POST)
    public SerializeObject  templateSwitch(@RequestHeader("accessToken") String accessToken,Integer id,Integer status){
        return rateSettingsService.templateSwitch(id,status);
    }

    /**
     * 内部接口调用
     * 根据type查询启用的优惠模板
     * @param type 1.买金优惠模板 2.回租优惠模板
     * @return
     */
    @RequestMapping(value = "/privilegeTemplate/findONTemplateByType" , method = GET)
    public SerializeObject<PrivilegeTemplateBean>  findONTemplateByType(Integer type){
        return rateSettingsService.findONTemplateByType(type);
    }


    /**
     * app接口  获取启用的并且方案类型非 不设置类型
     */
    @RequestMapping(value = "/privilegeTemplate/find" , method = GET)
    public SerializeObject<PrivilegeTemplateBean>  find(Integer type){
        return rateSettingsService.findONTemplateByType(type);
    }
}
